package com.jdwx.opengl.test;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author bai
 * @date 2020/6/30
 * @description
 * 非公平锁
 */
class FairLockNo {
    public static void main(String[] args) {
        PrintQueue printQueue = new PrintQueue();
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(new Job(printQueue));
        }

        for (int i=0;i<10;i++){
            threads[i].start();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Job implements Runnable{
    private PrintQueue printQueue;

    public Job(PrintQueue printQueue) {
        this.printQueue = printQueue;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始打印");
        printQueue.printDocument(new Object());
        System.out.println(Thread.currentThread().getName()+"打印结束");
    }
}

class PrintQueue {
    //非公平锁
    private Lock queueLock = new ReentrantLock(false);

    public void printDocument(Object document) {
        queueLock.lock();
        try {
            int duration =new Random().nextInt(10)+1;
            System.out.println(Thread.currentThread().getName() + "正在执行文件打印操作,需要"+duration);
            Thread.sleep(10 );

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            queueLock.unlock();
        }
        //打印两份
        queueLock.lock();
        try {
            int duration =new Random().nextInt(10)+1;
            System.out.println(Thread.currentThread().getName() + "正在执行文件打印操作,需要"+duration);
            Thread.sleep(10 );

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            queueLock.unlock();
        }
    }
}
